package com.ocom.exposeapi.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.ocom.common.HttpUtils;
import com.ocom.common.constant.ExposeApiUrl;
import com.ocom.common.entity.company.EntityComDockApi;
import com.ocom.common.entity.human.EntityBizLeaveApply;
import com.ocom.common.entity.mjrecode.MjRecord;
import com.ocom.common.enums.DockApiCodeEnum;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.company.GetComRequestRequest;
import com.ocom.common.request.company.GetPushByLineRequest;
import com.ocom.common.request.company.GetReplyApiParaRequest;
import com.ocom.common.request.exposeapi.ssgl.*;
import com.ocom.common.request.simple.SmsRequest;
import com.ocom.common.request.simple.ssgl.SSGLAttendanceRecordRequest;
import com.ocom.common.request.simple.ssgl.SSGLNewPersonInfoRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.response.GetComRequestResponse;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.utils.SignUtils;
import com.ocom.common.utils.ssgl.SSGLReturnDto;
import com.ocom.common.vo.GetFlowPushByLineVo;
import com.ocom.common.vo.human.UserInfoVo;
import com.ocom.common.vo.pyhandle.GetComWhiteListVo;
import com.ocom.common.vo.recode.AttendanceRecordVo;
import com.ocom.exposeapi.feign.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@Slf4j
@RestController
public class OcomKQController {

    @Autowired
    private CompanyClientService companyClientService;
    @Autowired
    private PayConfigClientService payConfigClientService;
    @Autowired
    private HumanFeignService humanFeignService;
    @Autowired
    private PayHandleClientService payHandleClientService;
    @Autowired
    private MjrecodeClientService mjrecodeClientService;

    @Autowired
    private MqSimple mqSimple;

    private static final String dockCode = "ocomkq";

    @PostMapping(ExposeApiUrl.URL_ExposeApi_ocomkqGetPersonVer)
    public Result getPersonVer(@Validated @RequestBody GetPersonVerRequest request) {

        SSGLReturnDto returnDto = new SSGLReturnDto();
        checkSign(request, request.getSvrId(), request.getComAppid(), DockApiCodeEnum.ocomkq_newPersonInfo.getValue(), request.getSign(), returnDto);
        if (null == returnDto.getEntityComDockApi() || null != returnDto.getResultEnum()) {
            return ResultUtil.error(returnDto.getResultEnum());
        }
        Result result = payConfigClientService.getXFWhiteVer(returnDto.getEntityComDockApi().getComId());
        if (200 != result.getCode() || null == result.getData()) {
            return ResultUtil.error(ResultEnum.Err_1000);
        }
        return result;
    }

    @PostMapping(ExposeApiUrl.URL_ExposeApi_ocomkqSetPersonVer)
    public Result setPersonVer(@Validated @RequestBody SetPersonVerRequest request) {
        SSGLReturnDto returnDto = new SSGLReturnDto();
        checkSign(request, request.getSvrId(), request.getComAppid(), DockApiCodeEnum.ocomkq_newPersonInfo.getValue(), request.getSign(), returnDto);
        if (null != returnDto.getResultEnum()) {
            return ResultUtil.error(returnDto.getResultEnum());
        }
        Result result = companyClientService.getApiPara(returnDto.getEntityComDockApi().getComId(), returnDto.getEntityComDockApi().getDockApiCode());
        if (200 != result.getCode()) {
            return ResultUtil.error(ResultEnum.Err_1000);
        }
        EntityComDockApi getApiPara = JSON.parseObject(JSON.toJSONString(result.getData()), EntityComDockApi.class);
        StringBuilder apiPara = new StringBuilder();
        String key = "personVer";

        if (StringUtils.isNotBlank(getApiPara.getApiPara())) {
            try {
                Map<String, Object> map = JSON.parseObject(getApiPara.getApiPara(), HashMap.class);
                map.put(key, request.getPersonVer());
                apiPara.append(JSON.toJSONString(map));
            } catch (Exception e) {
                e.printStackTrace();
                initApiPara(apiPara, key, request.getPersonVer());
            }

        } else {
            initApiPara(apiPara, key, request.getPersonVer());
        }

        companyClientService.setApiPara(returnDto.getEntityComDockApi().getComId(), DockApiCodeEnum.ocomkq_newPersonInfo.getValue(), apiPara.toString());

        return ResultUtil.success(request.getPersonVer());
    }

    @PostMapping(ExposeApiUrl.URL_ExposeApi_ocomkqDeptInfo)
    public Result deptInfo(@Validated @RequestBody DeptInfoRequest request) {
        SSGLReturnDto returnDto = new SSGLReturnDto();
        checkSign(request, request.getSvrId(), request.getComAppid(), DockApiCodeEnum.ocomkq_deptInfo.getValue(), request.getSign(), returnDto);
        if (null != returnDto.getResultEnum()) {
            return ResultUtil.error(returnDto.getResultEnum());
        }
        Result result = humanFeignService.GetDeptInfo(returnDto.getEntityComDockApi().getComId(), null, null);
        if (200 != result.getCode() || null == result.getData()) {
            return ResultUtil.error(ResultEnum.Err_1000);
        }
        return result;
    }


    @PostMapping(ExposeApiUrl.URL_ExposeApi_ocomkqAllPersonInfo)
    public Result allPersonInfo(@Validated @RequestBody AllPersonInfoRequest request) {
        SSGLReturnDto returnDto = new SSGLReturnDto();
        checkSign(request, request.getSvrId(), request.getComAppid(), DockApiCodeEnum.ocomkq_allPersonInfo.getValue(), request.getSign(), returnDto);
        if (null != returnDto.getResultEnum()) {
            return ResultUtil.error(returnDto.getResultEnum());
        }
        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setComId(returnDto.getEntityComDockApi().getComId());
        userInfoVo.setPage(request.getIndex());
        userInfoVo.setSize(request.getSize());
        userInfoVo.setStatus(request.getStatus());
        userInfoVo.setStartPid(request.getOldPid());

        Result result = humanFeignService.PersonnelGetPersonInfoById(userInfoVo);
        if (200 != result.getCode() || null == result.getData()) {
            return ResultUtil.error(ResultEnum.Err_1000);
        }

        return result;
    }

    @PostMapping(ExposeApiUrl.URL_ExposeApi_ocomkqNewPersonInfo)
    public Result newPersonInfo(@RequestBody SSGLNewPersonInfoRequest request) {
        try {
            log.info("ocomkqNewPersonInfo==Start=====参数：【{}】", request);
            String dockApiCode = DockApiCodeEnum.ocomkq_newPersonInfo.getValue();
            Result apiParaResult = companyClientService.getApiPara(request.getComId(), dockApiCode);
            if (200 != apiParaResult.getCode()) {
                return ResultUtil.error(ResultEnum.Err_1000);
            }
            EntityComDockApi getApiPara = JSON.parseObject(JSON.toJSONString(apiParaResult.getData()), EntityComDockApi.class);
            StringBuilder apiPara = new StringBuilder();
            Integer personVer = 0;
            int limit = Integer.MAX_VALUE;
            Map<String, Object> map = new HashMap<>();

            String key = "personVer";
            if (StringUtils.isNotBlank(getApiPara.getApiPara())) {
                map = JSON.parseObject(getApiPara.getApiPara(), HashMap.class);
                if (map.get(key)==null || !StringUtils.isNumeric(map.get(key).toString())) {
                    map.put(key, "0");
                }
                personVer = Integer.valueOf(map.get(key).toString());

            } else {
                initApiPara(apiPara, key,"0");
            }

            if (0 < request.getAutoSize()) {
                limit = request.getAutoSize();
            }

            Result personList = payHandleClientService.getComWhiteList(request.getComId(), personVer, limit);
            if (200 == personList.getCode()) {
                List<GetComWhiteListVo> getComWhiteListVos = JSON.parseArray(JSON.toJSONString(personList.getData()), GetComWhiteListVo.class);
                Optional<GetComWhiteListVo> getMaxId = getComWhiteListVos.stream().max(Comparator.comparing(GetComWhiteListVo::getId));
                if (getMaxId.isPresent()) {
                    Integer maxId = getMaxId.get().getId();
                    GetComRequestRequest getComRequestRequest = new GetComRequestRequest();
                    getComRequestRequest.setComId(request.getComId());
                    getComRequestRequest.setDockCode(dockCode);
                    getComRequestRequest.setDockApiCode(dockApiCode);
                    Result getComRequestResult = companyClientService.getComRequest(getComRequestRequest);
                    if (200 == getComRequestResult.getCode()) {
                        GetComRequestResponse getComRequestResponse = JSON.parseObject(JSON.toJSONString(getComRequestResult.getData()), GetComRequestResponse.class);
                        Map<String, Object> reqMap = new HashMap<>();
                        reqMap.put("comAppid", getComRequestResponse.getComAppid());
                        reqMap.put("whiteList", getComWhiteListVos);
                        log.info("ocomkqNewPersonInfo==postsJson==reqMap=====参数：【{}】,【{}】", getComRequestResponse.getRequestUrl(),reqMap);
                        String json = HttpUtils.postsJson(getComRequestResponse.getRequestUrl(), reqMap);
                        log.info("ocomkqNewPersonInfo==postsJson==json=====参数：【{}】", json);
                        Result results = JSON.parseObject(json, Result.class);
                        if (200 == results.getCode()) {
                            map.put(key, maxId);
                            apiPara = new StringBuilder(JSON.toJSONString(map));
                            companyClientService.setApiPara(request.getComId(), DockApiCodeEnum.ocomkq_newPersonInfo.getValue(), apiPara.toString());
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.info("ocomkqNewPersonInfo==Exception：【{}】", e);
            e.printStackTrace();
        }
        return ResultUtil.success();
    }

    @PostMapping(ExposeApiUrl.URL_ExposeApi_ocomkqGetPersonInfo)
    public Result getPersonInfo(@Validated @RequestBody GetPersonInfoRequest request) {
        SSGLReturnDto returnDto = new SSGLReturnDto();
        checkSign(request, request.getSvrId(), request.getComAppid(), DockApiCodeEnum.ocomkq_getPersonInfo.getValue(), request.getSign(), returnDto);
        if (null != returnDto.getResultEnum()) {
            return ResultUtil.error(returnDto.getResultEnum());
        }
        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setComId(returnDto.getEntityComDockApi().getComId());
        userInfoVo.setPId(request.getPId());
        userInfoVo.setOnlyOne(true);
        Result result = humanFeignService.PersonnelGetPersonInfo(userInfoVo);
        if (200 != result.getCode() || null == result.getData()) {
            return ResultUtil.error(ResultEnum.Err_1000);
        }
        return result;
    }

    @PostMapping(ExposeApiUrl.URL_ExposeApi_ocomkqAttendanceRecord)
    public Result attendanceRecord(@RequestBody SSGLAttendanceRecordRequest request) {
        try {
            log.info("ocomkqattendanceRecord==Start=====参数：【{}】", request);

            String dockApiCode = DockApiCodeEnum.ocomkq_attendanceRecord.getValue();
            Result apiParaResult = companyClientService.getApiPara(request.getComId(), dockApiCode);
            if (200 != apiParaResult.getCode()) {
                return ResultUtil.error(ResultEnum.Err_1000);
            }
            EntityComDockApi getApiPara = JSON.parseObject(JSON.toJSONString(apiParaResult.getData()), EntityComDockApi.class);
            StringBuilder apiPara = new StringBuilder();
            Long mjRecordVer = null;
            int size = Integer.MAX_VALUE;
            Map<String, Object> map = new HashMap<>();
            String key = "mjRecordVer";
            if (StringUtils.isNotBlank(getApiPara.getApiPara())) {

                map = JSON.parseObject(getApiPara.getApiPara(), HashMap.class);

                String recordVer = "0";
                if(map.get(key)!=null){
                    recordVer = map.get(key).toString();
                }
                if (!StringUtils.isNumeric(recordVer)) {
                    map.put(key, "0");
                }
                mjRecordVer = Long.valueOf(recordVer);

            } else {
                initApiPara(apiPara, key, "0");
            }

            if (0 < request.getAutoSize()) {
                size = request.getAutoSize();
            }

            AttendanceRecordVo attendanceRecordVo = new AttendanceRecordVo();
            attendanceRecordVo.setComId(request.getComId());
            attendanceRecordVo.setId(mjRecordVer);
            attendanceRecordVo.setDeviceVerType(9);
            attendanceRecordVo.setSize(size);
            log.info("ocomkqattendanceRecord==getAttendanceRecord=====参数：【{}】", attendanceRecordVo.toString());
            Result personList = mjrecodeClientService.getAttendanceRecord(attendanceRecordVo);
            if (200 == personList.getCode()) {
                List<MjRecord> mjRecordList = JSON.parseArray(JSON.toJSONString(personList.getData()), MjRecord.class);
                Optional<MjRecord> getMaxId = mjRecordList.stream().max(Comparator.comparing(MjRecord::getId));
                if (getMaxId.isPresent()) {
                    Long maxId = getMaxId.get().getId();
                    GetComRequestRequest getComRequestRequest = new GetComRequestRequest();
                    getComRequestRequest.setComId(request.getComId());
                    getComRequestRequest.setDockCode(dockCode);
                    getComRequestRequest.setDockApiCode(dockApiCode);

                    Result getComRequestResult = companyClientService.getComRequest(getComRequestRequest);
                    if (200 == getComRequestResult.getCode()) {
                        GetComRequestResponse getComRequestResponse = JSON.parseObject(JSON.toJSONString(getComRequestResult.getData()), GetComRequestResponse.class);
                        Map<String, Object> reqMap = new HashMap<>();
                        reqMap.put("comAppid", getComRequestResponse.getComAppid());
                        reqMap.put("accessRecord", mjRecordList);
                        log.info("ocomkqattendanceRecord==postsJson==reqMap=====参数：【{}】,【{}】", getComRequestResponse.getRequestUrl(), reqMap);
                        String json = HttpUtils.postsJson(getComRequestResponse.getRequestUrl(), reqMap);
                        log.info("ocomkqattendanceRecord==postsJson==json=====参数：【{}】", json);
                        Result results = JSON.parseObject(json, Result.class);
                        if (200 == results.getCode()) {
                            map.put(key, maxId);
                            apiPara = new StringBuilder(JSON.toJSONString(map));
                            companyClientService.setApiPara(request.getComId(), DockApiCodeEnum.ocomkq_attendanceRecord.getValue(), apiPara.toString());
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.info("ocomkqattendanceRecord==Exception：【{}】", e);
            e.printStackTrace();
        }
        return ResultUtil.success();
    }



    @PostMapping(ExposeApiUrl.URL_ExposeApi_ocomkqAuthLogin)
    public Result authLogin(@RequestBody KqTokenRequest request) {
        try {
            GetComRequestRequest getComRequestRequest = new GetComRequestRequest();
            getComRequestRequest.setComId(request.getComId());
            getComRequestRequest.setDockCode("ocomkq");
            getComRequestRequest.setDockApiCode("ocomkq#authLogin");
            Result getComRequestResult = companyClientService.getComRequest(getComRequestRequest);
            if (200 == getComRequestResult.getCode()) {
                GetComRequestResponse getComRequestResponse = JSON.parseObject(JSON.toJSONString(getComRequestResult.getData()), GetComRequestResponse.class);
                String res = HttpUtils.postsJson("http://kaoqin.ocomtraffic.com/prod-api/login",JSON.parseObject(getComRequestResponse.getRsaPri()));
                JSONObject jsonObject=JSON.parseObject(res);
                if(jsonObject.getInteger("code")==200){
                    return ResultUtil.success( jsonObject.getString("token"));
                }
                log.info("跳转考勤异常1  【{}】" ,res);
            }
        } catch (Exception e) {
            log.info("跳转考勤异常2  【{}】" ,e);
        }
        return ResultUtil.error(ResultEnum.Err_3);

    }

    private void checkSign(Object request, String svrId, String comAppId, String dockApiCode, String requestSign, SSGLReturnDto returnDto) {
        try {
            EntityComDockApi entityComDockApi = getReplyApiPara(svrId, comAppId, dockApiCode, 0, returnDto);
            String sign = "";
            if (null != entityComDockApi) {
                sign = SignUtils.createSign(request, null, entityComDockApi.getKey());
                returnDto.setEntityComDockApi(entityComDockApi);
            }

            if (StringUtils.isBlank(sign)) {
                returnDto.setResultEnum(ResultEnum.Err_3100);
            } else if (!requestSign.equals(sign)) {
                returnDto.setResultEnum(ResultEnum.Err_202);
            } else if (4 > returnDto.getReturnCode()) {
                returnDto.setResultEnum(ResultEnum.Err_201);
            } else if (4 == returnDto.getReturnCode()) {
                returnDto.setResultEnum(ResultEnum.Err_204);
            } else if (200 != returnDto.getReturnCode()) {
                returnDto.setResultEnum(ResultEnum.Err_204);
            }

        } catch (Exception e) {
            if (null == returnDto.getReturnCode()) {
                returnDto.setResultEnum(ResultEnum.Err_1000);
            }
            e.printStackTrace();
        }

    }

    private EntityComDockApi getReplyApiPara(String svrId, String appId, String dockApiCode, Integer keyType, SSGLReturnDto returnDto) {
        GetReplyApiParaRequest getReplyApiParaRequest = new GetReplyApiParaRequest();
        getReplyApiParaRequest.setDockCode(dockCode);
        getReplyApiParaRequest.setDockApiCode(dockApiCode);
        getReplyApiParaRequest.setSvrAppid(svrId);
        getReplyApiParaRequest.setComAppid(appId);
        getReplyApiParaRequest.setKeyType(keyType);

        log.info("getReplyApiPara:" + getReplyApiParaRequest.toString());
        Result getReplyApiParaResult = companyClientService.getReplyApiPara(getReplyApiParaRequest);

        log.info("getReplyApiParaResult:" + getReplyApiParaResult.toString());
        if (getReplyApiParaResult.getCode() != 200) {
            returnDto.setReturnCode(getReplyApiParaResult.getCode());
            returnDto.setReturnMessage(getReplyApiParaResult.getMsg());
        }
        return JSON.parseObject(JSON.toJSONString(getReplyApiParaResult.getData()), EntityComDockApi.class);
    }

    private void initApiPara(StringBuilder apiPara, String key, String ver) {
        apiPara.append("{");
        apiPara.append(key);
        apiPara.append(":");
        apiPara.append(ver);
        apiPara.append("}");

    }


    @PostMapping(ExposeApiUrl.URL_ExposeApi_gkdLeaveApplyNotice)
    public Result leaveApplyNotice(@RequestBody GetPushByLineRequest getPushByLineRequest){

        String sign = SignUtils.createSign(JSON.parseObject(JSON.toJSONString(getPushByLineRequest)),null,"key","cjKHmpHEnjxb8aNbaTzwfQTh8tXwCxSR");

        log.info("签名 【{}】",sign);
        log.info("处理短信通知 【{}】",getPushByLineRequest);
        if (!sign.equals(getPushByLineRequest.getSign())) {
            return ResultUtil.error(ResultEnum.Err_4041);
        }

        Result<GetFlowPushByLineVo> flowPushByLineVoResult = this.companyClientService.getPushByLine(getPushByLineRequest);
        log.info("发送短信人员 【审批】 【{}】【{}】",getPushByLineRequest,flowPushByLineVoResult);
        if(flowPushByLineVoResult.getCode()!=200){
            return  flowPushByLineVoResult;
        }

        GetFlowPushByLineVo getFlowPushByLineVo = flowPushByLineVoResult.getData();

        EntityBizLeaveApply entityBizLeaveApply = new EntityBizLeaveApply();
        entityBizLeaveApply.setComId(getFlowPushByLineVo.getComId());
        entityBizLeaveApply.setId(getFlowPushByLineVo.getBusinessId());
        Result<EntityBizLeaveApply> entityBizLeaveApplyResult = this.companyClientService.leavelApplyOne(entityBizLeaveApply);
        log.info("获取请假详情【{}】", JSON.toJSONString(entityBizLeaveApplyResult));

        EntityBizLeaveApply entityBizLeaveApplyA = entityBizLeaveApplyResult.getData();
        String content = String.format("%s天请假,%s,%s",entityBizLeaveApplyA.getDays(),entityBizLeaveApplyA.getReason(),getFlowPushByLineVo.getContent());
        for (GetFlowPushByLineVo.PushInfo push: getFlowPushByLineVo.getPushList()) {
            if(push.getPhone()==null || push.getPhone().length()!=11) continue;
            SmsRequest smsRequest = new SmsRequest();
            smsRequest.setSecretId("AKIDcLzhN0a8e8eChEnaQG8zpifcabfnu5JX");
            smsRequest.setSecretKey("Kh6VozznPn13ECwSlphN9jCVaRLTPIPa");
            smsRequest.setSignName("鑫澳康科技");
            smsRequest.setSdkAppId("1400314290");
            smsRequest.setTemplateId("2245787");
            smsRequest.setPhone(push.getPhone());

            smsRequest.getParams().add(getFlowPushByLineVo.getPName());
            smsRequest.getParams().add(getFlowPushByLineVo.getDeptName());
            smsRequest.getParams().add(DateUtil.format(getFlowPushByLineVo.getApplyTime(),"yyyy-MM-dd HH:mm:ss"));
            smsRequest.getParams().add(getFlowPushByLineVo.getFlowName());
            smsRequest.getParams().add(content);
            mqSimple.FySms(smsRequest);
        }

        return ResultUtil.success();
    }

}
